<template>
  <view class="Register">
    <view class="text-center margin-bottom-lg text-bold text-xl">
      用户注册
    </view>
    <form @submit="doRegister">

      <view class="cu-form-group">
        <view class="title">手机号</view>
        <input name="PHONENO" disabled v-model="phoneNum">
        <button open-type="getPhoneNumber" @getphonenumber="getPhoneNum" class='cu-btn bg-green shadow'>授权手机号</button>
      </view>

      <view class="cu-form-group">
        <view class="title">用户名称</view>
        <input placeholder="请输入用户名" name="USERNAME">
      </view>
	  <view class="cu-form-group">
	    <view class="text-sm">
	      <checkbox @tap="togglePolicyCheck"  :checked="isPolicyChecked" :class="{'checked': isPolicyChecked}" class='blue round margin-right-xs' style="transform: scale(0.7)"></checkbox>
	      同意<text class="text-blue" @tap="toPolicy">《系统隐私协议》</text>
	    </view>
	  </view>
		<view class="text-right text-green" @tap="toBindindex">
		  关联用户登录<text class="cuIcon-right"></text>
		</view>
      <view class="margin-top flex justify-center">
        <button form-type="submit" class="cu-btn bg-blue round shadow">注册账号</button>
      </view>

    </form>
  </view>
</template>

<script lang="ts" setup>
import {usePhoneNum} from "../bind/usePhoneNum";
import {register} from "../../api/auth";
import {useStore} from 'vuex'
import {usePolicyCheck} from "../bind/usePolicyCheck";

const {isPolicyChecked, togglePolicyCheck} = usePolicyCheck()

const {phoneNum, getPhoneNum} = usePhoneNum()

const {dispatch,getters} = useStore()

function toBindindex(){
	  uni.navigateTo({
	  	url:"/pages/bind/index"
	  })
  }


function toPolicy(){
  uni.navigateTo({
    url: '/pages/policy/index'
  })
}

function doRegister(e: any): void{
	if(isPolicyChecked.value){
		const form = e.detail.value
		
		if (!form.PHONENO){
		  uni.showToast({
		    title: '未授权手机号',
		    icon: 'error',
		    mask: true
		  })
		
		  return
		}
		
		if (!form.USERNAME) {
		  uni.showToast({
		    title: '请输入用户名',
		    icon: 'error',
		    mask: true
		  })
		
		  return
		}
		const {USERNAME, PHONENO} = form
		const {OPENID} = getters
		register({
		  USERNAME,
		  PHONENO,
		  OPENID,
		  SESSION_KEY: '',
		  ROLE_ID: 4,
		  OPERATOR_ID: 0
		}).then(res => {
		  if (res.ERROR[0].errcode == '0'){
		      uni.showToast({
		        title: '注册成功',
		        icon: 'success',
		        mask: true
		      })
		
		      setTimeout(() => {
		        dispatch('login').finally(() => {
		          uni.switchTab({
		            url: '/pages/account/index'
		          })
		        })
		      },500)
		  }else {
		      uni.showToast({
		        title: res.ERROR[0].error,
		        icon: 'none',
		        mask: true
		      })
		  }
		})
	}else{
		uni.showToast({
			title: "请先同意《隐私政策》",
			icon: 'none',
			mask: true
	  })
	}
 
}
</script>

<style scoped lang="scss">
.Register{
  box-sizing: border-box;
  padding-top: 100rpx;
}
</style>
